const express = require('express')
const router = express.Router()
const {logI} = require('../log.js')
const {retError, retSuccess} = require('../utils/ret')
const userDb = require('../db/user-db')
const checkType = require('../utils/checkType')
const checkToken = require('../utils/checkToken')
const checkDeviceNo = require('../utils/checkDeviceNo')
const moment = require('moment')

router
    .post('/', async(req, res) => {
        let {body: {maddr,token,meshUUID,deviceNo,buildingUUID}} = req
        logI('A-S', maddr, 'get_version', `${JSON.stringify(req.body)}`, 'null');
        try{
            const error = checkType.version(req.body)
            if(error){
                retError("get_version",maddr, 10001,  error.details[0].message, res);
            }else{
                let msg = {};
                msg = await checkToken(token,maddr);
                if(msg.code === 0){
                    const deviceInfo={
                        'maddr':maddr,
                        'deviceNo':deviceNo
                    }
                    let device={};
                    device = await checkDeviceNo(deviceInfo);
                    if(device.code === 0){
                        let ret={};
                        ret = await userDb.getVersion(buildingUUID,meshUUID);
                        if(ret.version_b === null && ret.version === null){
                            retError("get_version", maddr,10002, "invalid params", res);
                        }else{
                            let msgRet;
                            if(ret.version_b === null){
                                if(buildingUUID){
                                    retError("get_version", maddr,10002, "invalid params", res);
                                    return;
                                }
                                msgRet={
                                    'version':parseInt(ret.version)
                                }
                            }else if(ret.version === null){
                                msgRet={
                                    'version_b':parseInt(ret.version_b)
                                }
                            }else{
                                msgRet={
                                    'version':parseInt(ret.version),
                                    'version_b':parseInt(ret.version_b)
                                }
                            }
                            retSuccess("get_version", maddr,0, msgRet, res);
                        }
                    }else{
                        retError("get_version", maddr,device.code, device.body, res);
                    }
                }else{
                    retError("get_version", maddr,msg.code, msg.body, res);
                }
            }
        } catch (e) {
            retError("get_version", maddr,10001, e, res);
        }

    })
module.exports = router
